<template>
  <a-space direction="vertical" :style="{ width: '100%' }">
    <a-upload
      :custom-request="customRequest"
      :fileList="file ? [file] : []"
      :show-file-list="false"
      @change="onChange"
    >
      <template #upload-button>
        <div
          :class="`arco-upload-list-item${
            file && file.status === 'error'
              ? ' arco-upload-list-item-error'
              : ''
          }`"
        >
          <div
            class="arco-upload-list-picture custom-upload-avatar"
            v-if="file && file.url"
          >
            <img :src="file.url" />
            <div class="arco-upload-list-picture-mask">
              <IconEdit />
            </div>
          </div>
          <div class="arco-upload-picture-card" v-else>
            <div class="arco-upload-picture-card-text">
              <IconPlus />
              <div style="margin-top: 10px; font-weight: 600">上传</div>
            </div>
          </div>
        </div>
      </template>
    </a-upload>
  </a-space>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { uploadUsingPost } from '@/service/backend/fileInfoController';
import { Message } from '@arco-design/web-vue';

const emit = defineEmits(['update:modelValue']);

const file = ref();

const onChange = (_, currentFile) => {
  file.value = {
    ...currentFile
  };
};

const customRequest = async option => {
  try {
    const res = await uploadUsingPost({}, option.fileItem.file);
    if (res.data && res.code === 0) {
      emit('update:modelValue', res.data);
      Message.success(`${option.fileItem.name}上传成功`);
    }
  } catch (e) {
    Message.error('头像上传失败,' + e.message);
  }
};
</script>
